
import { Component, OnInit, ElementRef, AfterViewInit, ViewChild } from '@angular/core';
import { Http, Response } from '@angular/http';
import { DxDataGridComponent } from 'devextreme-angular';
import 'rxjs/add/operator/map';
import { Subject } from 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
//增删改查共通Service
import { CommService } from '../../comm/comm.service';
import { ReportUrls } from '../../comm/report.urls.conf';
import { CTS } from '../../model/report/cts';
import { CTSChart } from '../../model/report/cts-chart'
import { SubArea } from '../../model/report/sub-area';
import { Resource } from '../../model/report/resource';
import { QueryModel } from '../../model/report/query-model';
import { ResponseModel } from '../../model/comm/response-model';
import { ChartOptionCreater } from '../../model/comm/chart-option-creater';
import { Shift } from '../../model/report/shift';
import * as c3 from 'c3';
import 'rxjs/add/operator/toPromise';
declare const $: any;
import * as moment from 'moment';
declare var swal: any;
import * as Enumerable from 'linq';
import { TVResource } from 'app/ptpmc/model/comm/tv-resource';
export class StatObject {
    count: String;
    min: String;
    max: String;
    percent: String;
    avg: String;
    stdev: String;
    equipment: String;
    ratect: String;
};
@Component({
    selector: 'app-report-cts',
    templateUrl: './cts.component.html',
    styleUrls: ['./cts.component.scss']
})

export class CTSComponent implements OnInit {
    title = 'CT统计';
    public ctsList: CTS[];
    public ctsGridList: CTS[];
    showloading = true;

    /*生产线 - 班次*/
    public subAreaItems: SubArea[];
    public shiftItems: any[];
    public equipemntItems: TVResource[] = [];

    public subAreaSelected: any;
    public shiftSelected: any;

    public minValue = 0;
    public maxValue = 1000;
    public timeLength = 1;
    public percent = 0.00;
    public chartList: CTSChart[] = [];
    public chartOption: any;
    public chartLineOption: any;
    public statObject: StatObject = new StatObject();
    public equipmentSelected: TVResource;
    constructor(private commServices: CommService) {
    }
    //组件初始化
    ngOnInit() {
        this.commServices.initDatePicker($('#DateTimeRange'), 'YYYY-MM-DD HH:mm');
        this.shiftItems = this.commServices.shifts;
        this.shiftSelected = this.shiftItems[0];
        this.subAreaItems = this.commServices.getSubAreas();
        this.subAreaSelected = this.subAreaItems[0];
        this.equipemntItems = this.commServices.getTVResourceBySubArea(this.subAreaItems[0].subArea);
        this.equipmentSelected = this.equipemntItems[0];
        this.statObject.equipment = '';
        this.statObject.avg = '0';
        this.statObject.count = '0';
        this.statObject.max = '0';
        this.statObject.min = '0';
        this.statObject.percent = '0';
        this.statObject.ratect = '0';
        this.statObject.stdev = '0';
    }


    onSubAreaSelectedChange(subArea: any): void {
        this.equipemntItems = this.commServices.getTVResourceBySubArea(subArea.value.subArea);
        this.equipmentSelected = this.equipemntItems[0];
    }
    /**
     * 获取表格数据
     */
    getReportData(): void {
        const queryModel: QueryModel = new QueryModel();
        queryModel.dateTimeRange = this.getTime('DateTimeRange');
        queryModel.querySubAreaIds = [this.subAreaSelected.subArea];
        queryModel.queryResourceIds = [this.equipmentSelected.resource];
        queryModel.shift = this.shiftSelected.shiftId;
        queryModel.minValue = this.minValue;
        queryModel.maxValue = this.maxValue;
        queryModel.percent = this.percent;
        queryModel.filterValue = this.timeLength;
        this.commServices
            .getList(queryModel, ReportUrls.CTSUrl)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    model.data.BaseData.forEach(item =>{
                        if(queryModel.querySubAreaIds[0].slice(0,2) === 'GF'){
                            var sub: string = '';
                            sub = item.subArea.replace(/(^\s*)|(\s*$)/g, "");
                            switch(sub){
                                case 'GFAL1': sub += '_装配主线';  break;
                                case 'GFBU1': sub += '_测试线';  break;
                                case 'GFCL1': sub += '_CASE 机加工线';  break;
                                case 'GFCR1': sub += '_行星齿轮组分装线';  break;
                                case 'GFCS1': sub += '_中间支撑架分装线';  break;
                                case 'GFDH1': sub += '_飞轮盘减震器壳体分装线';  break;
                                case 'GFHL1': sub += '_HOUSING 机加工线';  break;
                                case 'GFTC1': sub += '_壳体分装线';  break;
                                case 'GFTD1': sub += '_中间轴&差速器分装线';  break;
                            }
                            item.subArea = sub;
                        }
                    });
                    this.ctsList = model.data.BaseData;
                    this.chartList = model.data.chartlist;
                    this.statObject.avg = (<number>model.data.avg).toFixed(2);
                    this.statObject.count = model.data.count;
                    this.statObject.equipment = model.data.equipment;
                    this.statObject.max = model.data.max;
                    this.statObject.min = model.data.min;
                    this.statObject.percent = ((<number>model.data.percent) * 100).toFixed(2);
                    this.statObject.ratect = (<number>model.data.ratect).toFixed(5);
                    this.statObject.stdev = (<number>model.data.stdev).toFixed(5);
                    this.showCharts();
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
    }
    /**ECharts图表相关*/
    chartsMap = new Map<number, any>();
    onChartInit(index: number, echartsIntance: any): void {
        this.chartsMap.set(index, echartsIntance);
        Observable.fromEvent(window, 'resize')
            .debounceTime(100) // 以免频繁处理
            .subscribe((event) => this.chartsMap.forEach((v, k) => v.resize()));
    }

    selectedIndexChange(tabIndex: any) {
        this.chartsMap.get(tabIndex).resize();
    }
    showCharts(): void {
        const legend = new Array();
        const scatterData = new Array();
        const xData = new Array();
        const yData = new Array();
        const yDataLine = new Array();
        this.chartList.forEach(e => {
            const scatter: any[] = [];
            const percent: number = Number.parseFloat((e.percent * 100).toFixed(2));
            scatter.push(e.ct);
            scatter.push(percent);
            scatterData.push(scatter);
            xData.push(e.ct);
            yData.push(percent);
        });
        legend.push('概率');
        const yBean = {
            name: '概率',
            type: 'line',
            data: yData
        };
        yDataLine.push(yBean);
        this.chartOption = ChartOptionCreater.createScatterChartsOption('', '', '%', legend, scatterData);
        this.chartLineOption = ChartOptionCreater.createChartsOption('', '', '%', '', legend, xData, yDataLine, null);
    }
    getGridData() {
        let last: CTS;
        let tempList: CTS[] = [];
        tempList = Enumerable.from(this.ctsList).orderBy(u => u.resource).thenBy(u => u.logTime).toArray();
    }
    /**
     * 获取TimeRange的值
     * @param id id
    */
    getTime(id: any): String {
        const timerange: String = $('#' + id).val();
        return timerange;
    }

    protected exportData() {
        const files = new Array<any>();
        const queryModelArray = new Array<any>();
        queryModelArray.push('时间:' + this.getTime('DateTimeRange'));
        queryModelArray.push('区域:' + this.subAreaSelected.subArea);
        queryModelArray.push('设备:' + this.equipmentSelected.equipment);
        queryModelArray.push('班次:' + (this.shiftSelected.shiftId === '-1' ? '全部' : this.shiftSelected.shiftId === '1' ? '早班' : '中班'));
        queryModelArray.push('时间宽度:' + this.timeLength + '秒');
        queryModelArray.push('最大值:' + this.maxValue + '秒' + ' , 最小值:' + this.minValue + '秒');
        queryModelArray.push('筛选百分比:' + this.percent + '%');
        this.chartsMap.forEach((v, k) => {
            const picBase64Info = v.getDataURL();
            files.push({ chartsTitle: k, chartsEncodeStr: picBase64Info });
        });
        this.commServices.exportPdf({ reportTitle: this.title, charts: files, queryModel: queryModelArray });
    }

    onExporting(e) {
        e.fileName = e.fileName + new Date().toISOString().replace(/[\-\:\.]/g, '').split('T')[0];
    }
}
